package com.jyniubi.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jyniubi.base.result.R;
import com.jyniubi.base.utils.JwtUtils;
import com.jyniubi.core.hfb.RequestHelper;
import com.jyniubi.core.pojo.entity.UserAccount;
import com.jyniubi.core.service.UserAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author jyzhang
 * @since 2024-04-27
 */
@Api(tags = "充值模块")
@Slf4j
@RestController
@RequestMapping("/api/core/userAccount")
public class ApiUserAccountController {
    @Resource
    private UserAccountService userAccountService;

    @ApiOperation("提现回调")
    @PostMapping("/notifyWithdraw")
    public String notifyWithdraw(HttpServletRequest request){
        return userAccountService.notifyWithdraw(request);
    }

    @ApiOperation("用户提现")
    @GetMapping("/auth/withdraw")
    public R withdraw(@RequestHeader(value = "token",required = false) String token,BigDecimal amount){
        String form = userAccountService.withdraw(token,amount);
        return R.ok().data("form",form);
    }

    @ApiOperation("查询账户余额")
    @GetMapping("/getAmount")
    public R getAmount(@RequestHeader(value = "token",required = false) String token){
        Long userId = JwtUtils.getUserId(token);
        UserAccount userAccount = userAccountService.getOne(Wrappers.lambdaQuery(UserAccount.class).eq(UserAccount::getUserId, userId).select(UserAccount::getAmount));
        return R.ok().data("amount",userAccount.getAmount()).data("userId",userId);
    }


    @ApiOperation("充值回调")
    @PostMapping("/notify")
    public String rechargeNotify(HttpServletRequest request){
        Map<String, Object> map = RequestHelper.switchMap(request.getParameterMap());
        log.info("用户充值异步回调：" + JSON.toJSONString(map));
        // 验签
        if (RequestHelper.isSignEquals(map)){
            //验证异步回调充值结果
            if ("0001".equals(map.get("resultCode"))){
                return userAccountService.rechargeNotify(map);
            } else {
                log.info("用户充值异步回调充值失败：" + JSON.toJSONString(map));
                return "success";
            }
        } else {
            log.info("用户充值异步回调签名错误：" + JSON.toJSONString(map));
            return "fail";
        }
    }

    @ApiOperation("充值")
    @PostMapping("/recharge")
    public R recharge(@RequestHeader(value = "token",required = false) String token,
                      BigDecimal amount){
        String form = userAccountService.recharge(token,amount);
        return R.ok().data("form",form);
    }

}

